// src/js/uniBridge.js
const dbName = 'star';
const callbacks = new Set()

// 注册监听
export function onMessage(fn) {
    callbacks.add(fn)
}

// 注销监听
export function offMessage(fn) {
    callbacks.delete(fn)
}

// 向所有已注册的回调派发消息
function dispatchMessage(msg) {
    callbacks.forEach(fn => {
        try {
            fn(msg)
        } catch (e) {
            console.error('[uniBridge] 消息处理失败:', e)
        }
    })
}

// 定义接收消息的统一入口
if (!window.receiveMessageFromApp) {
    window.receiveMessageFromApp = function (msg) {
        try {
            console.log('[uniBridge] 收到 uni-app 消息:', msg)
            dispatchMessage(msg)
        } catch (e) {
            console.error('[uniBridge] 消息解析失败:', e)
        }
    }
}

// 初始化数据库
export function initDb() {
    sendMessage({action: 'initDb', sql: '1'});
}


// 封装 Select SQL 消息发送
export function sendSelectSql(sql) {
    sendMessage({action: 'selectSql', sql: sql});
}

// 封装 Update SQL 消息发送
export function sendUpdateSql(sql) {
    sendMessage({action: 'updateSql', sql: sql});
}

// 封装 Delete SQL 消息发送
export function sendDeleteSql(sql) {
    sendMessage({action: 'deleteSql', sql: sql});
}

// 发送消息到 uni-app 的 webview
export function sendMessage({action, sql}) {
    const payload = {
        action,
        dbName,
        sql
    };
    console.log('window.uni', window.uni);
    if (window.uni && window.uni.webView) {
        window.uni.webView.postMessage({data: payload});
    } else {
        console.warn('[uniBridge] uni.webView 未定义，无法发送消息');
    }
}

// 让组件也能拿到 uni（如果需要）
export function getUni() {
    return window.uni || {}
}
